package com.etalk.crm.serviceImpl;

import com.alibaba.fastjson.JSON;
import com.etalk.crm.dao.MenuInfoMapper;
import com.etalk.crm.dao.StoresMapper;
import com.etalk.crm.dao.UserMapper;
import com.etalk.crm.pojo.MenuInfo;
import com.etalk.crm.pojo.Store;
import com.etalk.crm.pojo.User;
import com.etalk.crm.pojo.UserSelect;
import com.etalk.crm.service.UserService;
import com.etalk.crm.utils.EncryptAndDecrypt;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @author Jordan
 */
@Service
public class UserServiceImpl implements UserService {
    protected static final Logger logger= LogManager.getLogger(UserServiceImpl.class);
    @Resource
    private UserMapper userMapper;

    @Resource
    StoresMapper storesMapper;

    @Resource
    private  MenuInfoMapper menuInfoMapper;

    /**
     * 查询登录人信息
     * @param loginName 登录名称
     * @param loginPwd 登录密码
     * @return 登录是否成功
     */
    @Override
    public boolean login(String loginName,String loginPwd, HttpSession session) {
        if (StringUtils.isEmpty(loginName) || StringUtils.isEmpty(loginPwd)){
            return false;
        }
        String loginNamePwdToken= EncryptAndDecrypt.MD5(loginName.toUpperCase()+loginPwd);
        User user=userMapper.selectLoginInfoByLoginNamePwdToken(loginNamePwdToken);
        if (!StringUtils.isEmpty(user) && user.getId()>0){
            session.setAttribute("userid", user.getId());
            session.setAttribute("loginname", user.getLoginName());
            session.setAttribute("roleId", user.getRoleId());
            session.setAttribute("storesId", user.getStoresId());
            session.setAttribute("username", user.getCnName());
            session.setAttribute("enName", user.getEnName());
            session.setAttribute("robCase", user.getRobCase());
            session.setAttribute("accountId", user.getAccountId());
            session.setAttribute("storeType", user.getStores().getType());
            session.setAttribute("shareAreaId", user.getStores().getShareAreaId());
            session.setAttribute("accountId", user.getAccountId());
            session.setAttribute("personId",user.getPersonId());
            /*Stores stores=storesMapper.selectStoreInfoById(user.getStoresId());
            session.setAttribute("storesName", stores.getName());
            session.setAttribute("storesEnName", stores.getEnName());
            session.setAttribute("hflag", stores.getHomeFlag());
            session.setAttribute("roleflag", stores.getRoleFlag());
            session.setAttribute("shareAreaId", stores.getShareAreaId());
            session.setAttribute("menus", menuInfoMapper.searchMenuInfoByUsersId(user.getId()));*/
            //菜单权限
	        List<MenuInfo> menuList = menuInfoMapper.searchMenuInfoByUsersId(user.getId());
            Map<Integer,String>menuMap = new HashMap<>(menuList.size());
            for(MenuInfo menu : menuList){
                menuMap.put(menu.getId(),menu.getMenuName());
            }
            session.setAttribute("menuMap",menuMap);
            Map<String,Object> map=new HashMap<>(4);
            map.put("loginId",user.getId());
            map.put("loginName",user.getLoginName());
            map.put("roleId",user.getRoleId());
            map.put("storesId",user.getStoresId());
            session.setAttribute("userToken",EncryptAndDecrypt.encrypt(JSON.toJSONString(map)));
            map.put("expiredTime", DateUtils.addHours(new Date(),10));
            session.setAttribute("expiredToken",EncryptAndDecrypt.encrypt(JSON.toJSONString(map)));
	        logger.info("URLEncoder :  "+ EncryptAndDecrypt.encrypt(JSON.toJSONString(map)));

          /*  try {
                String userToken=EncryptAndDecrypt.encrypt(JSON.toJSONString(map));
                logger.info("userToken:  "+ userToken);
                userToken= URLEncoder.encode(userToken,"UTF-8");
                logger.info("URLEncoder :  "+ userToken);
                logger.info(userToken+"  :  "+EncryptAndDecrypt.decrypt(URLDecoder.decode(userToken, "UTF-8")));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }*/
            return true;
        }
        return false;
    }

    /**
     * ssc 列表
     * @return
     */
    @Override
    public List<User> sscList() {
        return userMapper.selectSSc();
    }

    /**
     * 修改密码
     * @param userId 用户id
     * @param oldPwd 旧密码
     * @param newPwd 新密码
     * @return 修改记录数
     */
    @Override
    public int modifyPassword(Integer userId,String oldPwd,String newPwd){
        return userMapper.updatePassword(userId,oldPwd,newPwd);
    }

    @Override
    public List<User> ccSscList(List<Integer> roleList) {
        return userMapper.ccSscList(roleList);
    }

    @Override
    public List<User> sscAndSecList() {
        return userMapper.sscAndSecList();
    }

    @Override
    public List<User> ccList(HttpSession session,Map<String,Object> map) {
        List<User> list = new ArrayList<>();
        Integer storesId = null;
        if (Integer.parseInt(session.getAttribute("storeType").toString()) <= 4) {
             if (Integer.parseInt(session.getAttribute("roleId").toString()) == 2 || (Integer.parseInt(session.getAttribute("roleId").toString()) == 12)
             && map.get("stroresIds") == null) {
                 storesId = Integer.parseInt(session.getAttribute("storesId").toString());
             }else{
                 if(Integer.parseInt(session.getAttribute("storesId").toString()) != 1){
                     storesId = Integer.parseInt(session.getAttribute("storesId").toString());
                 }
             }
        }
        if (Integer.parseInt(session.getAttribute("roleId").toString()) == 2) {
            User user = new User();
            user.setId(Integer.parseInt(session.getAttribute("userid").toString()));
            user.setLoginName(session.getAttribute("loginname").toString());
            list.add(user);
            return list;
        } else {
             if (Integer.parseInt(session.getAttribute("storesId").toString()) == 1) {//如果没有设置分店，并且是总部查询，则查询所有门店CC
                if (map.get("stroresIds") == null) {
                    List<Integer> storesList = storesMapper.selectEtalkListId();
                    map.put("stroresIds",storesList);
                }
            } else {//所有非总部查询CC
                storesId = Integer.parseInt(session.getAttribute("storesId").toString());
            }
        }
        map.put("storesId",storesId);
        return userMapper.ccList(map);
    }

    @Override
    public List<User> bccList() {
        return userMapper.bccList();
    }

    @Override
    public List<User> ltList() {
        return userMapper.ltList();
    }

    @Override
    public List<User> getCcList(Integer storesId) {
        HashMap<String,Object> map = new HashMap();
        map.put("storesId",storesId);
        return userMapper.ccList(map);
    }

    @Override
    public List<User> selectUserNameAndIdList(Integer storesId, List<Integer> listRoleId) {
        return userMapper.selectUserNameAndIdList(storesId,listRoleId);
    }

    @Override
    public User selectByPrimaryKey(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    /**
     * 查询cc列表，专用于select标签使用
     * @param listId 已选中的cc id
     * @return
     */
    @Override
    public List<Map<String,Object>> searchCcSelectList(List<Integer> listId){
        List<Map<String,Object>> resultList=new ArrayList<>();
        List<UserSelect> list=userMapper.selectCcList();
        List<Store> storeList=userMapper.selectStoreList();
        if (list!=null && list.size()>0){
            int storesId=0;
            String storeName="";
            Map<String,Object> firstMap;
            List<Map<String,Object>> childList=null;
            for (UserSelect user : list) {
                if (user.getStoresId() != storesId) {
                    storesId = user.getStoresId();
                    firstMap = new HashMap<>(3);
                    storeName="";
                    for (Store store : storeList) {
                        if (store.getId() == storesId) {
                            storeName = store.getName();
                            storeList.remove(store);
                            break;
                        }
                    }
                    firstMap.put("name", storeName);
                    childList = new ArrayList<>();
                    firstMap.put("list", childList);
                    resultList.add(firstMap);
                }
                Map<String, Object> userMap = new HashMap<>(3);
                userMap.put("id", user.getId());
                userMap.put("name", user.getLoginName());
                userMap.put("selected", false);
                if (listId != null && listId.size() > 0) {
                    for (Integer id : listId) {
                        if (id.equals(user.getId())) {
                            userMap.put("selected", true);
                            listId.remove(id);
                            break;
                        }
                    }
                }
                childList.add(userMap);
            }
        }
        return resultList;
    }

    /**
     * 查询ssc选择列表
     * @param listId 已选id
     * @return
     */
    @Override
    public List<UserSelect> searchSscSelectList(List<Integer> listId){
        List<UserSelect> list=userMapper.selectSscList();
        if (listId!=null && listId.size()>0){
            for (UserSelect user:list){
                for (Integer id:listId){
                    if (id.equals(user.getId())){
                        user.setSelected(true);
                    }
                }
            }
        }

        return list;
    }
}
